package com.b2.service.impl;


import com.b2.exception.BaseException;
import com.b2.pojo.dto.WebUserEditDto;
import com.b2.pojo.dto.WebUserLoginDto;
import com.b2.pojo.dto.WebUserRegister;
import com.b2.pojo.entity.WebUser;
import com.b2.result.Result;
import com.b2.service.WebUserService;
import com.b2.mapper.WebUserMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * @author ThinkBook
 * @description 针对表【web_user(web端用户表)】的数据库操作Service实现
 * @createDate 2024-07-01 10:18:42
 */
@Service
public class WebUserServiceImpl extends ServiceImpl<WebUserMapper, WebUser>
        implements WebUserService {

    @Autowired
    private WebUserMapper webUserMapper;

    /**
     * 盐值，混淆密码
     */
    private static final String SALT = "miku";

    /**
     * 注册
     *
     * @param webUserRegister
     * @return
     */
    @Override
    public Result<Long> register(WebUserRegister webUserRegister) {
        String userAccount = webUserRegister.getUserAccount();
        String userPassword = webUserRegister.getUserPassword();
        String checkPassword = webUserRegister.getCheckPassword();
        //1.校验参数
        if (StringUtils.isAnyEmpty(userAccount, userPassword, checkPassword)) {
            return Result.error("参数为空");
        }
        if (userAccount.length() < 4) {
            return Result.error("账号过短");
        }
        if (userPassword.length() < 6 || checkPassword.length() < 6) {
            return Result.error("密码过短");
        }
        //  5. 账户不包含特殊字符
        // 匹配由数字、小写字母、大写字母组成的字符串,且字符串的长度至少为1个字符
        String pattern = "[0-9a-zA-Z]+";
        if (!userAccount.matches(pattern)) {
            return Result.error("用户账号包含特殊字符");
        }
        // 6. 密码和校验密码相同
        if (!userPassword.equals(checkPassword)) {
            return Result.error("密码和校验密码不相同");
        }
        //账号不能重复
        Long count = webUserMapper.selectCount(new LambdaQueryWrapper<WebUser>().eq(WebUser::getUserAccount, userAccount));
        if (count > 0) {
            return Result.error("账号已存在");
        }

        //加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 7. 插入数据
        WebUser webUser = new WebUser();
        webUser.setUserAccount(userAccount);
        webUser.setUserPassword(encryptPassword);
        //默认为用户权限
        if (webUserRegister.getUserRole() == null) {
            webUser.setUserRole(0);
        }
        webUser.setUserRole(webUser.getUserRole());
        webUser.setCreateTime(LocalDateTime.now());

        boolean result = this.save(webUser);
        if (!result) {
            return Result.error("注册失败");
        }
        return Result.success(webUser.getId());
    }

    /**
     * 登录
     *
     * @param webUserLogin
     * @return
     */
    @Override
    public WebUser login(WebUserLoginDto webUserLogin) {
        String userAccount = webUserLogin.getUserAccount();
        String userPassword = webUserLogin.getUserPassword();
        //1.校验参数
        if (StringUtils.isAnyEmpty(userAccount, userPassword)) {
            throw new BaseException("参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BaseException("账号过短");
        }
        //  5. 账户不包含特殊字符
        // 匹配由数字、小写字母、大写字母组成的字符串,且字符串的长度至少为1个字符
        String pattern = "[0-9a-zA-Z]+";
        if (!userAccount.matches(pattern)) {
            throw new BaseException("用户账号包含特殊字符");
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        //查询
        WebUser webUser = this.getOne(new LambdaQueryWrapper<WebUser>()
                .eq(WebUser::getUserAccount, userAccount)
                .eq(WebUser::getUserPassword, encryptPassword));
        if (webUser == null) {
            throw new BaseException("用户名或密码错误");
        }
        return webUser;
    }

    /**
     * 修改web用户信息
     *
     * @param webUserEditDto
     * @return
     */
    @Override
    public Result<Boolean> editWebUser(WebUserEditDto webUserEditDto) {
        Long id = webUserEditDto.getId();
        String userName = webUserEditDto.getUserName();
        String userAccount = webUserEditDto.getUserAccount();
        String oldPassword = webUserEditDto.getOldPassword();
        String newPassword=webUserEditDto.getNewPassword();
        //校验参数是否正确
        if (id==null){
            throw new RuntimeException("id不能为空");
        }
        //1.校验参数

        if (userAccount.length() < 4) {
            throw new BaseException("账号过短");
        }
        //  5. 账户不包含特殊字符
        // 匹配由数字、小写字母、大写字母组成的字符串,且字符串的长度至少为1个字符
        String pattern = "[0-9a-zA-Z]+";
        if (!userAccount.matches(pattern)) {
            throw new BaseException("用户账号包含特殊字符");
        }

        // 2. 加密
         oldPassword = DigestUtils.md5DigestAsHex((SALT + oldPassword).getBytes());

        //查询
        WebUser webUser = this.getById(id);
        if (!webUser.getUserPassword().equals(oldPassword)){
            return Result.error("你输入的密码错误");
        }
        newPassword = DigestUtils.md5DigestAsHex((SALT + newPassword).getBytes());

        //修改信息
        boolean update = update(Wrappers.<WebUser>lambdaUpdate().eq(WebUser::getId, id)
                .set(StringUtils.isNotBlank(userName), WebUser::getUserName, userName)
                .set(StringUtils.isNotBlank(userAccount),WebUser::getUserAccount, userAccount)
                .set(StringUtils.isNotBlank(newPassword),WebUser::getUserPassword, newPassword));
        return Result.success(update);
    }
}




